<!-- 图表 》 条形图 -->

<template>
  <EasyChart :baseOption="OPTION" :option="option" :onClick="toClick" />
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import mixChart from '../mixChart'

const name = 'ChartBar'

const PERCENT_SERIE = {
  showBackground: true,
  backgroundStyle: { color: '#eee' },
  label: { formatter: '{c}%' },
}

const PERCENT_TOOPTIP = {
  trigger: 'item',
  formatter: (param) => `${param.name}<br />${param.marker} ${param.value}%`,
}

const PERCENT_GRID_BAR = {
  right: 50,
}

const PERCENT_GRID_COLUMN = {
  top: 50,
}

const PERCENT_AXIS = {
  max: 100,
}

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name,

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [mixChart],

  /**
   * 属性注册
   */
  props: CORE.WEB[name],

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 颜色对象
     */
    colorObj: () => CORE.WEB.BASE.COLOR.BAR,

    /**
     * 颜色键名
     */
    colorKey() {
      const keyList = Object.keys(this.colorObj)
      return keyList.find((key) => this[key]) || keyList[0]
    },

    /**
     * 基础配置
     */
    OPTION() {
      const { colorObj, colorKey, $options: { name }, noTip, percent, init } = this
      const tooltip = noTip ? { show: false } : percent ? PERCENT_TOOPTIP : {}
      const grid = percent ? name === 'ChartBar' ? PERCENT_GRID_BAR : PERCENT_GRID_COLUMN : {}
      const xAxis = percent && name === 'ChartBar' ? PERCENT_AXIS : {}
      const yAxis = percent && name === 'ChartColumn' ? PERCENT_AXIS : {}
      const obj = percent ? PERCENT_SERIE : {}
      const barWidth = this[`${name.slice(5).toLowerCase()}Width`]
      const color = colorObj[colorKey]
      const serie = CORE.merge({}, init.series[0], obj, { barWidth, itemStyle: { color } })
      return CORE.merge({}, init, { tooltip, grid, xAxis, yAxis, series: [serie] })
    },

    /**
     * 图表配置
     */
    option() {
      const { xData, dataList, serie, diy } = this

      const option = {
        yAxis: { data: xData },
        series: [
          { ...serie, data: dataList },
        ],
      }

      return CORE.merge(option, diy)
    },
  },
}
</script>
